//index.js
//获取应用实例
import Dialog from '../../plugins/vant-weapp/dist/dialog/dialog';
var api = require('../../utils/api.js');
import cookies from '../../plugins/weapp-cookie/weapp-cookie'
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    bindPhone: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    sendCodeText: '发送验证码',
    phoneErrorMessage: '',
    codeErrorMessage: '',
    verifyCode: '',
    sendCodeStatus: false,
    remainSeconds: 30,
    shareOpenId: null
  },
  onLoad: function (options) {
    var dno = options.dno ? options.dno : '449665FB45A90EFD'
    app.globalData.dno = dno
    if (options.hasOwnProperty('openId')) {
      this.setData({
        shareOpenId: options.openId
      })
    }
    console.log(options.openId, app.globalData.swUser)
    if(app.globalData.swUser) {
      wx.switchTab({
        url: '/pages/index/index',
      })
      return true
    }
    this.setData({
      userInfo: app.globalData.swUser,
      hasUserInfo: app.globalData.hasUserInfo,
      bindPhone: app.globalData.bindPhone,
      phone: '',
      verifyCode: '',
      sendCodeStatus: false
    });
    if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          this.wechatLogin(res);
        }
      })
    }
  },
  updatePhone: function(event) {
    this.setData({
      phone: event.detail
    });
  },
  updateVerifyCode: function(event) {
    this.setData({
      verifyCode: event.detail
    })
  },
  sendVerifyCode: function(event) {
    var phone = this.data.phone;
    var that = this;
    if (!(/^1[34578]\d{9}$/.test(phone))) {
      this.setData({
        phoneErrorMessage: '手机号格式错误，请重新输入'
      });
      return false;
    }
    wx.request({
      url: api.sendVerifyCodeUrl,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      data: {
        phone: that.data.phone
      },
      success: function(res) {
        if(res.data.status == 'success') {
          setTimeout(that.updateSendCodeBtn, 1000);
        }
      }
    })
  },
  bindPhone: function() {
    var phone = this.data.phone;
    var verifyCode = this.data.verifyCode;
    if (!(/^1[34578]\d{9}$/.test(phone))) {
      this.setData({
        phoneErrorMessage: '手机号格式错误，请重新输入'
      });
      return false;
    }
    
    // if(!verifyCode) {
    //   this.setData({
    //     codeErrorMessage: '验证码不能为空'
    //   });
    //   return false;
    // }
    var that = this;
    wx.showLoading({
      title: '绑定中',
    })
    wx.requestWithCookie({
      url: api.bindPhoneUrl,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      data: {
        phone: that.data.phone
      },
      dataType: 'json',
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 'success') {
          var swUser = res.data.data;
          app.globalData.swUser = swUser;
          app.globalData.hasUserInfo = true;
          app.globalData.bindPhone = true;
          wx.setStorageSync('swUser', swUser);
          wx.setStorageSync('key', data)
          wx.switchTab({
            url: '/pages/index/index'
          });
        } else {
          wx.showToast({
            title: '绑定失败',
          })
        }
      },
      fail: function () {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
        })
      }
    })
  },
  updateSendCodeBtn: function() {
    var remainSeconds = this.data.remainSeconds;
    --remainSeconds;
    if(remainSeconds <= 0) {
      this.setData({
        remainSeconds: 20,
        sendCodeText: '发送验证码',
        sendCodeStatus: false
      });
      return false;
    }
    this.setData({
      sendCodeStatus: true
    });
    this.setData({
      remainSeconds: remainSeconds,
      sendCodeText: remainSeconds + '秒'
    });
    setTimeout(this.updateSendCodeBtn, 1000);
  },
  getUserInfo: function (e) {
    if (e.detail.errMsg == 'getUserInfo:ok') {
      app.globalData.userInfo = e.detail;
      this.wechatLogin(e.detail);
    }
  },
  wechatLogin: function (detail) {
    wx.showLoading({
      title: '注册中',
    })
    var that = this;
    wx.login({
      success: res => {
        var shareOpendId = that.data.shareOpendId
        if(shareOpendId) {
          wx.request({
            url: api.ShareRegister,
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            data: {
              code: res.code,
              iv: detail.iv,
              encryptedData: detail.encryptedData,
              openId: that.data.shareOpendId,
              // appId: app.globalData.appId
            },
            dataType: 'json',
            success: function (res) {
              wx.hideLoading()
              if (res.data.Code === 1) {
                wx.showToast({
                  title: '信息获取成功',
                  duration: 1000
                })
                var swUser = res.data.Entity;
                app.updateUser(swUser)

                that.setData({
                  hasUserInfo: true,
                  userInfo: swUser
                });
                // if(swUser.phone) {
                app.globalData.bindPhone = true;
                wx.switchTab({
                  url: '/pages/index/index'
                });
                // }
                // wx.switchTab({
                //   url: '/pages/index/index'
                // });
              } else {
                wx.showToast({
                  title: '注册失败',
                })
              }
            },
            fail: function () {
              wx.hideLoading();
              wx.showToast({
                title: '网络错误',
                duration: 1000
              })
            }
          })
        } else {
          wx.request({
            url: api.registerUrl,
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            data: {
              code: res.code,
              iv: detail.iv,
              encryptedData: detail.encryptedData,
              // appId: app.globalData.appId
              dno: app.globalData.dno
            },
            dataType: 'json',
            success: function (res) {
              wx.hideLoading()
              if (res.data.Code === 1) {
                wx.showToast({
                  title: '信息获取成功',
                  duration: 1000
                })
                var swUser = res.data.Entity;
                app.updateUser(swUser)

                that.setData({
                  hasUserInfo: true,
                  userInfo: swUser
                });
                // if(swUser.phone) {
                app.globalData.bindPhone = true;
                wx.setStorageSync('start-dno', app.globalData.dno)
                wx.switchTab({
                  url: '/pages/index/index',
                });
                // }
                // wx.switchTab({
                //   url: '/pages/index/index'
                // });
              } else {
                wx.showToast({
                  title: '注册失败',
                })
              }
            },
            fail: function () {
              wx.hideLoading();
              wx.showToast({
                title: '网络错误',
                duration: 1000
              })
            }
          })
        }
      }
    });
  }
})
